package com.ruoyi.celoan.service.statistics;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.celoan.dto.ExPrivatelyOperatedStatisticsDto;
import com.ruoyi.celoan.entity.DalianDataReportKeyEntity;
import com.ruoyi.celoan.entity.ExPrivatelyOperatedStatisticsEntity;
import com.ruoyi.celoan.handanUtils.HanDanHttpUtils;
import com.ruoyi.celoan.handanUtils.response.CountryPlatformResponse;
import com.ruoyi.celoan.mapper.EcPrivatelyOperatedStatisticsMapper;
import com.ruoyi.celoan.mapper.statistics.ExTradeEffectCreditStatisticsOrgMapper;
import com.ruoyi.celoan.service.ExPrivatelyOperatedStatisticsService;
import com.ruoyi.celoan.service.IEcDalianDataReportLogsService;
import com.ruoyi.celoan.util.ListUtils;
import com.ruoyi.manage.enterprise.domain.EcEnterpriseInformation;
import com.ruoyi.manage.enterprise.service.IEcEnterpriseInformationService;
import com.ruoyi.manage.organization.service.IOcOrderLoanService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ExPrivatelyOperatedStatisticsServiceImpl extends ServiceImpl<EcPrivatelyOperatedStatisticsMapper, ExPrivatelyOperatedStatisticsEntity> implements ExPrivatelyOperatedStatisticsService {
    private static final Logger log = LoggerFactory.getLogger(ExPrivatelyOperatedStatisticsServiceImpl.class);
    @Autowired
    private IEcDalianDataReportLogsService dalianDataReportLogsService;
    private static String url = "/api/upload/privatelyOperatedStatistics";

    @Autowired
    private ExTradeEffectCreditStatisticsOrgMapper exTradeEffectCreditStatisticsOrgMapper;

    @Autowired
    private IEcEnterpriseInformationService iEcEnterpriseInformationService;

    @Autowired
    private IOcOrderLoanService iOcOrderLoanService;

    /**
     * operatedStatisticsEntity 统计实体类
     * entity 最新的上个月的数据
     */
    public List<ExPrivatelyOperatedStatisticsEntity> calculateOperatedStatistics() {
//        查询判断当月数据是否存在
        boolean exists = this.lambdaQuery().eq(ExPrivatelyOperatedStatisticsEntity::getExternalSystemId, DateUtil.format(DateUtil.date(), "yyyyMM")).exists();
        if(exists){
            return Collections.emptyList();
        }

        ExPrivatelyOperatedStatisticsEntity entity = this.lambdaQuery()
                .orderByDesc(ExPrivatelyOperatedStatisticsEntity::getExternalSystemId)
                .last("LIMIT 1")
                .one();

        //        当月日期
        LocalDate now = LocalDate.now();
        LocalDateTime startOfMonth = now.with(TemporalAdjusters.firstDayOfMonth())
                .atStartOfDay(); // 月初 00:00:00
        LocalDateTime endOfMonth = now.with(TemporalAdjusters.lastDayOfMonth())
                .atTime(23, 59, 59); // 月末 23:59:59


        ExPrivatelyOperatedStatisticsEntity operatedStatisticsEntity = new ExPrivatelyOperatedStatisticsEntity();
        operatedStatisticsEntity.setExternalSystemId(DateUtil.format(DateUtil.date(), "yyyyMM"));
        operatedStatisticsEntity.setAreaCode("130400");
        operatedStatisticsEntity.setSettlingPlatform("1306");


//       注册企业数量
        String enterpriseNum = entity.getRegisteredEnterpriseNum();
        BigDecimal decimal = new BigDecimal(enterpriseNum);
        long enterPriseCount = iEcEnterpriseInformationService.count(
                Wrappers.<EcEnterpriseInformation>lambdaQuery()
                        .between(EcEnterpriseInformation::getCreateTime, startOfMonth, endOfMonth));
        BigDecimal finalCount = decimal.add(BigDecimal.valueOf(enterPriseCount));
        operatedStatisticsEntity.setRegisteredEnterpriseNum(String.valueOf(finalCount));


        JSONObject loanJson = exTradeEffectCreditStatisticsOrgMapper.countDistinctEnterpriseInCurrentMonth();
        BigDecimal loanEnterpriseNumDecimal = new BigDecimal(entity.getLoanEnterpriseNum());
        BigDecimal finalEnterpriseNum = loanEnterpriseNumDecimal.add(BigDecimal.valueOf(loanJson.getInteger("count")));
        //   用信民营企业数量
        operatedStatisticsEntity.setLoanEnterpriseNum(String.valueOf(finalEnterpriseNum));
//       当月用信企业数量
        operatedStatisticsEntity.setMonthLoanEnterpriseNum(loanJson.getString("count"));


//        授信民营企业数量
        JSONObject creditJson = exTradeEffectCreditStatisticsOrgMapper.countDistinctEnterpriseWithCreditInCurrentMonth();
        BigDecimal creditEnterpriseNumDecimal = new BigDecimal(entity.getCreditEnterpriseNum());
        BigDecimal finalCreditEnterpriseNum = creditEnterpriseNumDecimal.add(BigDecimal.valueOf(creditJson.getInteger("count")));
        operatedStatisticsEntity.setCreditEnterpriseNum(String.valueOf(finalCreditEnterpriseNum));

//       授信金额
        BigDecimal creditLoanAmountDecimal = new BigDecimal(entity.getCreditLoanAmount());
        BigDecimal finalCreditLoanAmount = creditLoanAmountDecimal.add(creditJson.getBigDecimal("creditAmount"));
        operatedStatisticsEntity.setCreditLoanAmount(String.valueOf(finalCreditLoanAmount));



//        当月放贷金额
        operatedStatisticsEntity.setMonthLoanAmount(loanJson.getString("loanAmount"));


        JSONObject loanAvgSummaryJson = exTradeEffectCreditStatisticsOrgMapper.getMonthlyLoanAvgSummary();

//        用信笔数
        BigDecimal loanNumDecimal = new BigDecimal(entity.getLoanNum());
        BigDecimal finalLoanNum = loanNumDecimal.add(loanAvgSummaryJson.getBigDecimal("count"));
        operatedStatisticsEntity.setLoanNum(String.valueOf(finalLoanNum));
        //        企业用信金额
        BigDecimal loanAmountDecimal = new BigDecimal(entity.getLoanAmount());
        BigDecimal finalloanAmount = loanAmountDecimal.add(loanJson.getBigDecimal("loanAmount"));
        operatedStatisticsEntity.setLoanAmount(String.valueOf(finalloanAmount));
        //        当月放贷数量
        operatedStatisticsEntity.setMonthLoanNum(loanAvgSummaryJson.getString("count"));
//        放款平均利率
        operatedStatisticsEntity.setAverageLendingRate(loanAvgSummaryJson.getString("loanRateAvg"));

        JSONObject creditAvgSummary = exTradeEffectCreditStatisticsOrgMapper.getMonthlyCreditAvgSummary();
//       信用授信金额
        //        当月授信数量
        operatedStatisticsEntity.setMonthCreditLoanNum(creditAvgSummary.getString("count"));
//        当月授信金额
        operatedStatisticsEntity.setMonthCreditLoanAmount(creditAvgSummary.getString("creditAmount"));
//       企业授信金额
        BigDecimal creditAmountDecimal = new BigDecimal(entity.getCreditAmount());
        BigDecimal finalCreditAmount = creditAmountDecimal.add(creditAvgSummary.getBigDecimal("creditAmount"));
        operatedStatisticsEntity.setCreditAmount(String.valueOf(finalCreditAmount));
//        授信用信数量
        BigDecimal creditLoanNumDecimal = new BigDecimal(entity.getCreditLoanNum());
        BigDecimal finalCreditLoanNum = creditLoanNumDecimal.add(creditAvgSummary.getBigDecimal("count"));
        operatedStatisticsEntity.setCreditLoanNum(String.valueOf(finalCreditLoanNum));


        JSONObject applySummaryJson = exTradeEffectCreditStatisticsOrgMapper.getMonthlyFinancingApplySummary();
        BigDecimal financingNeedAmountDeciaml = new BigDecimal(entity.getFinancingNeedsAmount());
        BigDecimal finalApplyAmount = financingNeedAmountDeciaml.add(applySummaryJson.getBigDecimal("applyAmount"));
//        融资需求金额
        operatedStatisticsEntity.setFinancingNeedsAmount(String.valueOf(finalApplyAmount));
//        当月融资需求金额
        operatedStatisticsEntity.setMonthFinancingNeedsAmount(applySummaryJson.getString("applyAmount"));
//        当月融资需求数量
        operatedStatisticsEntity.setMonthFinancingNeedsNum(applySummaryJson.getString("count"));
//        融资需求数量
        BigDecimal financingNeedNum = new BigDecimal(entity.getFinancingNeedsNum());
        BigDecimal finalFinancingNeedNum = financingNeedNum.add(applySummaryJson.getBigDecimal("count"));
        operatedStatisticsEntity.setFinancingNeedsNum(String.valueOf(finalFinancingNeedNum));

        operatedStatisticsEntity.setIsflag(0);

        List<ExPrivatelyOperatedStatisticsEntity> list = new ArrayList<>();
        list.add(operatedStatisticsEntity);

        return list;

    }

    public void getHanDanDataReport(String interfaceName, DalianDataReportKeyEntity entity, String areaCode, String token) {
        String startDate = LocalDateTime.now().plusDays(-2L).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        QueryWrapper<ExPrivatelyOperatedStatisticsEntity> queryWrapper = new QueryWrapper();
        queryWrapper.eq("area_code", areaCode);
        queryWrapper.eq("isflag", Integer.valueOf(0));
        log.info("开始时间：" + startDate);

        List<ExPrivatelyOperatedStatisticsEntity> list = calculateOperatedStatistics();
//        List<ExPrivatelyOperatedStatisticsEntity> list = ((EcPrivatelyOperatedStatisticsMapper) this.baseMapper).selectList((Wrapper) queryWrapper);
         this.saveBatch(list);
        List<ExPrivatelyOperatedStatisticsDto> listDto = Convert.toList(ExPrivatelyOperatedStatisticsDto.class, list);
        if (CollUtil.isNotEmpty(listDto)) {
            List<List<ExPrivatelyOperatedStatisticsDto>> retList = ListUtils.splitList(listDto, 1);
            this.dalianDataReportLogsService.addLogs(interfaceName + "接口上报数据开始", listDto.size() + "条");
            String date = LocalDate.now().toString();
            List<Long> updateList = new ArrayList<>();
            for (int i = 0; i < retList.size(); i++) {
                try {
                    List<ExPrivatelyOperatedStatisticsDto> reportList = retList.get(i);
                    List<Long> addlist = (List<Long>) reportList.stream().map(ret -> ret.getId()).collect(Collectors.toList());
                    this.dalianDataReportLogsService.addLogs(interfaceName + "明细日期:" + date + "上报id为：", JSONObject.toJSONString(addlist));
                    log.info("请求参数:" + JSONObject.toJSONString(reportList));
                    CountryPlatformResponse response = HanDanHttpUtils.creditStatistics(url, JSONObject.toJSONString(reportList), token);
                    this.dalianDataReportLogsService.addLogs(interfaceName + "明细返回结果:", JSONObject.toJSONString(response));
                    if (response.isApiStatus()) {
                        updateList.addAll(addlist);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    log.info("数据上报异常:" + e.getMessage());
                    this.dalianDataReportLogsService.addLogs(interfaceName + "上报数据上报错误信息", JSONObject.toJSONString(e.getMessage()));
                }
            }
            if (CollUtil.isNotEmpty(updateList)) {
                UpdateWrapper<ExPrivatelyOperatedStatisticsEntity> updateWrapper = new UpdateWrapper();
                updateWrapper.in("id", updateList);
                updateWrapper.set("isflag", Integer.valueOf(1));
                update((Wrapper) updateWrapper);
                this.dalianDataReportLogsService.addLogs(interfaceName + "上报数据上报成功条数:", updateList.size() + "条");
            }
        }
    }
}


/* Location:              D:\tuodayun\workspace\work\celoan-third-data-report-service-2.0.0-SNAPSHOT.jar!\BOOT-INF\classes\com\celoan\service\statistics\ExPrivatelyOperatedStatisticsServiceImpl.class
 * Java compiler version: 8 (52.0)
 * JD-Core Version:       1.1.3
 */
